let queenNum = document.querySelector('.queenNum');
let solve = document.querySelector('.solve');

let im = new Image();
im.src = 'firefox.png';
const boardWidth = im.width = 20;
const boardHeight = im.height = 20;

im.onload = function() {
    console.log('width = ' + boardWidth, 'height = ' + boardHeight);
}

solve.addEventListener('click', function() {
    n = Number(queenNum.value);
    if (n < 4) {
        alert('number is too small');
        return;
    }

    solveAns = solveNQueens(n);
    for (let i = 0; i < solveAns.length; ++i) {
        paintBoard(n, solveAns[i]);
    }
});

function paintBoard(n, queens) {
    let p = document.createElement('div');
    let canvas = document.createElement('canvas');
    p.appendChild(canvas);
    document.querySelector('.queen').appendChild(p);
    const ctx = canvas.getContext('2d');

    ctx.fillStyle = 'rgb(0, 0, 0)';
    ctx.fillRect(0, 0, n*boardWidth, n*boardHeight);

    for (let i = 0; i < n; ++i) {
        for (let j = 0; j < n; ++j) {
            let color = 'rgb(0, 0, 0)';
            if ((i + j) % 2 === 0) {
                color = 'rgb(255, 206, 158)';
            } else {
                color = 'rgb(209, 139, 71)';
            }
            // ctx.beginPath();
            ctx.fillStyle = color;
            ctx.fillRect(j*boardWidth, i*boardHeight, boardWidth, boardHeight);

            if (queens[j][i] === 'Q') {
                ctx.drawImage(im, j*boardWidth, i*boardHeight);
            }
        }
    }
}

var solveNQueens = function(n) {
    let ans = [];
    let queens = new Array(n);
    for (let i = 0; i < n; ++i) {
        queens[i] = new Array(n).fill('.');
    }
    let columns = new Set();
    let digAdd = new Set();
    let digSub = new Set();

    let dfs = function(row) {
        if (n === row) {
            let temp = new Array(n);
            for (let i = 0; i < n; ++i) {
                temp[i] = queens[i].join('');
            }
            ans.push(temp);
            return;
        }

        for (let i = 0; i < n; ++i) {
            if (columns.has(i) || digAdd.has(row + i) || digSub.has(row - i)) {
                continue;
            }

            columns.add(i);
            digAdd.add(row + i);
            digSub.add(row - i);
            queens[row][i] = 'Q';

            dfs(row + 1);

            columns.delete(i);
            digAdd.delete(row + i);
            digSub.delete(row - i);
            queens[row][i] = '.';
        }
    }

    dfs(0);
    return ans;
};